<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon>
                <Document />
              </el-icon>
              <span>配置文件</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.configCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon>
                <Link />
              </el-icon>
              <span>域名数量</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.domainCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon>
                <Share />
              </el-icon>
              <span>负载均衡</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.upstreamCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon>
                <Monitor />
              </el-icon>
              <span>服务器数量</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.serverCount }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Nginx 配置部分 -->
    <el-card class="nginx-config-card">
      <template #header>
        <div class="card-header">
          <span>Nginx 配置 （版本：{{ nginxVersion }}）</span>
          <el-button type="primary" @click="handleSaveConfig" :loading="loading">保存配置</el-button>
        </div>
      </template>

      <el-form ref="formRef" :model="nginxConfig" label-width="170px" class="nginx-form">

        <el-form-item label="是否使用 Docker">
          <el-switch v-model="nginxConfig.isDockerized" />
          
        </el-form-item>
        <template v-if="nginxConfig.isDockerized">
          <el-form-item label="推荐的Docker启动命令:">
            <el-input
              type="textarea"
              :rows="3"
              readonly
              :value="'docker run -d \
  --name nginx \
  -p 80:80 -p 443:443 \
  -v /path/to/nginx/conf:/etc/nginx \
  -v /path/to/nginx/logs:/var/log/nginx \
  nginx:latest'"
            />
          <div class="tip-text">
            <el-alert
              title="提示：SSL证书文件需要放在已映射的配置目录中，例如: /path/to/nginx/conf"
              type="warning"
              :closable="false"
              show-icon
            />
          </div>
          </el-form-item>
          <el-form-item label="Docker 容器名称">
            <el-input v-model="nginxConfig.dockerContainerName" placeholder="例如: nginx">
              <template #append>
                <el-button @click="testContainer">测试容器</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="配置文件宿主机路径">
            <el-input v-model="nginxConfig.dockerHostPath" placeholder="例如: /path/to/nginx/" />
          </el-form-item>

          <el-form-item label="配置文件容器内路径">
            <el-input v-model="nginxConfig.dockerContainerPath" placeholder="例如: /etc/nginx/" />
          </el-form-item>

          <el-form-item label="日志文件宿主机路径">
            <el-input v-model="nginxConfig.dockerHostLogPath" placeholder="例如: /path/to/nginx/logs" />
          </el-form-item>

          <el-form-item label="日志文件容器内路径">
            <el-input v-model="nginxConfig.dockerContainerLogPath" placeholder="例如: /var/log/nginx" />
          </el-form-item>

          
          <el-form-item label="证书文件宿主机路径" prop="dockerHostSslPath">
            <el-input v-model="nginxConfig.dockerHostSslPath" placeholder="宿主机上的证书文件路径，例如：/data/docker/nginx/ssl" />
          </el-form-item>
          <el-form-item label="证书文件容器内路径" prop="dockerContainerSslPath">
            <el-input v-model="nginxConfig.dockerContainerSslPath" placeholder="容器内的证书文件路径，例如：/etc/nginx/ssl" />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="Nginx 可执行文件路径">
            <el-input v-model="nginxConfig.nginxExec" placeholder="例如: /usr/sbin/nginx">
              <template #append>
                <el-button @click="testNginxExec">测试</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="Nginx 工作目录">
            <el-input v-model="nginxConfig.nginxCwd" placeholder="例如: /etc/nginx" />
          </el-form-item>

          <el-form-item label="配置文件目录">
            <el-input v-model="nginxConfig.nginxConfDir" placeholder="例如: /etc/nginx/conf.d">
              <template #append>
                <el-button @click="testConfDir">测试</el-button>
              </template>
            </el-input>
          </el-form-item>
        </template>
      </el-form>
      
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Document, Link, Share, Monitor } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { NginxService } from '@/services/nginx.service'

const loading = ref(false)

// 统计数据
const stats = ref({
  configCount: 0,
  domainCount: 0,
  upstreamCount: 0,
  serverCount: 0
})

// Nginx 配置
const nginxConfig = ref({
  nginxExec: '',
  nginxCwd: '',
  nginxConfDir: '',
  isDockerized: false,
  dockerContainerName: '',
  dockerHostPath: '',
  dockerContainerPath: '',
  dockerHostLogPath: '',
  dockerContainerLogPath: '',
  dockerHostSslPath: '',
  dockerContainerSslPath: ''
})

const nginxVersion = ref('')

// 加载配置和统计信息
const loadData = async () => {
  try {
    loading.value = true

    // 加载 Nginx 配置
    const config = await NginxService.getNginxConfig()
    nginxConfig.value = {
      ...nginxConfig.value,
      ...config
    }

    // 加载统计信息
    const configs = await NginxService.getAllConfigs()

    // 计算统计数据
    stats.value.configCount = configs.length
    stats.value.domainCount = configs.reduce((count, config) => {
      return count + (config.servers?.reduce((domains, server) => {
        return domains + (server.server_name?.length || 0)
      }, 0) || 0)
    }, 0)
    stats.value.upstreamCount = configs.reduce((count, config) => {
      return count + (config.upstreams?.length || 0)
    }, 0)
    stats.value.serverCount = configs.reduce((count, config) => {
      return count + (config.upstreams?.reduce((servers, upstream) => {
        return servers + (upstream.servers?.length || 0)
      }, 0) || 0)
    }, 0)

    // 加载 Nginx 版本
    const version = await NginxService.getNginxVersion()
    nginxVersion.value = version

  } catch (error) {
    console.error('Failed to load data:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 保存 Nginx 配置
const handleSaveConfig = async () => {
  try {
    loading.value = true
    await NginxService.updateNginxConfig(nginxConfig.value)
    ElMessage.success('配置保存成功')
  } catch (error) {
    console.error('Failed to save config:', error)
    ElMessage.error('保存配置失败')
  } finally {
    loading.value = false
  }
}

// 测试 Nginx 可执行文件
const testNginxExec = async () => {
  try {
    loading.value = true
    const result = await NginxService.testNginxExec(nginxConfig.value.nginxExec)
    ElMessage.success(result.message || 'Nginx 可执行文件测试成功')
  } catch (error) {
    ElMessage.error('Nginx 可执行文件测试失败')
  } finally {
    loading.value = false
  }
}

// 测试配置目录
const testConfDir = async () => {
  try {
    loading.value = true
    const result = await NginxService.testConfDir(nginxConfig.value.nginxConfDir)
    ElMessage.success(result.message || '配置目录测试成功')
  } catch (error) {
    ElMessage.error('配置目录测试失败')
  } finally {
    loading.value = false
  }
}

// 测试 Docker 容器
const testContainer = async () => {
  try {
    loading.value = true
    const result = await NginxService.testDockerContainer(nginxConfig.value.dockerContainerName)
    ElMessage.success(result.message || 'Docker 容器测试成功')
  } catch (error) {
    ElMessage.error('Docker 容器测试失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-value {
  font-size: 36px;
  font-weight: bold;
  color: var(--el-color-primary);
  text-align: center;
  line-height: 1.5;
}

.nginx-config-card {
  margin-top: 20px;
}

.nginx-config-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nginx-form {
  max-width: 800px;
  margin: 0 auto;
}

:deep(.el-divider__text) {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.tip-text {
  margin-top: 10px;
  color: #666;
  font-size: 13px;
}
</style>